from fastapi import APIRouter, WebSocket, WebSocketDisconnect, HTTPException
from app.utils.logger import setup_logger
import json
from app.services.aliyun_voice_clone import AliyunSpeechSynthesizer

# 创建日志记录器
logger = setup_logger("aliyun_voice_clone_router")

# 创建路由器
router = APIRouter(
    prefix="/aliyun",
    tags=["aliyun"],
    responses={404: {"description": "Not found"}},
)

# 创建语音合成器实例
synthesizer = AliyunSpeechSynthesizer()

@router.websocket("/voice_clone/ws")
async def websocket_endpoint(websocket: WebSocket):
    # 获取 API Key
    api_key = websocket.query_params.get("api_key")
 

    await websocket.accept()
    logger.info("新的语音克隆连接已建立")

    try:
        # 等待客户端消息
        data = await websocket.receive_text()
        request_data = json.loads(data)

        # 验证请求数据
        if not all(k in request_data for k in ['api_key', 'voice', 'text']):
            await websocket.send_json({"error": "缺少必要参数: api_key, voice, text"})
            return

        # 提取参数
        api_key = request_data.get('api_key')
        voice_id = request_data.get('voice')
        text = request_data.get('text')
        model = "cosyvoice-v1"

        # 发送处理中的状态
        await websocket.send_json({
            "type": "result",
            "text": ""
        })

        # 调用语音合成类的方法
        success, response, audio_data = synthesizer.synthesize_speech(api_key, voice_id, text, model)

        if success:
            # 将音频数据转换为base64
            base64_audio = synthesizer.get_base64_audio(api_key, voice_id, text, model)

            if base64_audio:
                response["audio"] = base64_audio
                # 发送响应
                await websocket.send_json(response)
            else:
                await websocket.send_json({"error": "音频编码失败"})
        else:
            # 发送错误响应
            await websocket.send_json(response)

    except WebSocketDisconnect:
        logger.info("客户端断开连接")
    except Exception as e:
        logger.error(f"WebSocket 出错: {str(e)}")